﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace zielonka.co.uk.extensions.system
{
    //  Description:	Finds the nearest common ancestor for type based on the inheritance hierarchy.
    /*
     * target.GetType().FindCommonAncestor(Source.GetType());
     */

    public static partial class TypeExtensions
    {
        public static Type FindCommonAncestor(this Type type, Type targetType)
        {
            if (targetType.IsAssignableFrom(type))
                return targetType;

            var baseType = targetType.BaseType;
            while (baseType != null && !baseType.IsPrimitive)
            {
                if (baseType.IsAssignableFrom(type))
                    return baseType;
                baseType = baseType.BaseType;
            }
            return null;
        }
    }
}
